const Router = require("@koa/router");
const { order, ObjectId } = require("../models/mongo");
const { bodyParser } = require("@koa/bodyparser");

const router = new Router({
    prefix: "/api",
});

router.post("/order", async (ctx) => {
    const count = await order.countDocuments();
    const orderResult = await order.aggregate([
        {
            $lookup: {
                from: "users",
                localField: "author_id",
                foreignField: "_id",
                as: "author",
            },
        },
    ])

        .toArray();
    ctx.body = { orderResult };

});
// 删除
router.post("/delOrder", bodyParser(), async (ctx) => {
    const { id } = ctx.request.body;  // 从请求体中获取订单ID
    const delOrder = await order.deleteOne({ _id: new ObjectId(id) }); // 删除订单

    if (delOrder.deletedCount > 0) {
        ctx.body = {
            code: 200,
            message: "删除成功",
        };
    } else {
        ctx.body = {
            code: 400,
            message: "订单不存在",
        };
    }
});

// 修改
router.post("/updateOrder", bodyParser(), async (ctx) => {
    const { id, state } = ctx.request.body;  // 获取订单ID和要更新的状态
    const modifyOrder = await order.updateOne({ _id: new ObjectId(id) }, {
        $set: { state }  // 更新状态字段
    });

    if (modifyOrder.matchedCount > 0) {
        ctx.body = {
            code: 200,
            message: "success",
        };
    } else {
        ctx.body = {
            code: 400,
            message: "订单不存在",
        };
    }
});

// 新增
router.post("/addOrder", bodyParser(), async (ctx) => {
    const {
        publishedAt,
        time,
        phone,
        au,
        state,
        region,
        detailAddress,
        orderItems,
        totalAmount,
        userid
    } = ctx.request.body;

    // 创建一个订单数据对象
    const orderData = {
        publishedAt,
        time,
        phone,
        au,
        state,
        address: { region, detailAddress },  // 地址信息
        orderItems,  // 商品信息数组
        totalAmount,  // 总金额
        userid,  // 用户ID
    };

    try {
        // 插入订单数据到数据库
        const addOrder = await order.insertOne(orderData);
        console.log('addOrder', addOrder);
        
        if (addOrder.insertedCount > 0) {
            ctx.body = {
                code: 200,
                message: "success",
            };
        } else {
            ctx.body = {
                code: 500,
                message: "订单保存失败",
            };
        }
    } catch (err) {
        console.error('数据库插入失败', err);
        ctx.body = {
            code: 500,
            message: "数据库插入失败",
        };
    }
});


// 查询，通过title，au，phone筛选
router.post("/selectOrder", bodyParser(), async (ctx) => {
    try {
      let { filterQuery } = ctx.request.body;
  
      if (filterQuery._id) {
        filterQuery._id = new ObjectId(filterQuery._id); // **确保 _id 为 ObjectId**
      }
  
      const total = await order.countDocuments(filterQuery);
      const list = await order.find(filterQuery).toArray();
  
      ctx.body = {
        code: 200,
        message: "success",
        total,
        list,
      };
    } catch (error) {
      console.error("查询订单失败：", error);
      ctx.body = {
        code: 500,
        message: "服务器错误",
        error: error.message,
      };
    }
  });

module.exports = router;
